package com.hades.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class HelloServlet implements Servlet {
    public HelloServlet() {
        System.out.println("Hades : First, Construct.");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("Hades : Second, init.");
        System.out.println("HelloServlet程序的别名是" + servletConfig.getServletName());
        System.out.println("初始化参数username的值是" + servletConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是" + servletConfig.getInitParameter("url"));
        System.out.println("ServletContest对象是" + servletConfig.getServletContext());
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hades : Third, service. Hello Servlet.");
        //想要获取请求的类型是get还是post，可以调用servletRequest的getMethod()方法
        //但传入的参数servletRequest不能直接用，但可以通过以下这种方式调用（强制类型转换）
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        if("GET".equals(method)){
            doGet();
        } else if("POST".equals(method)){
            doPost();
        }
    }

    public void doGet(){
        System.out.println("GET请求对应的代码执行了。");
    }

    public void doPost(){
        System.out.println("POST请求对应的代码执行了。");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("Hades : Fourth, destroy.");
    }
}
